package com.kou.backend.handler;

import com.kou.backend.error.CommonErrorEnum;
import com.kou.backend.exception.CommonException;
import com.kou.backend.resposne.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 统一异常处理
 *
 * @author: Kou
 * @since: 2023/8/26 19:47
 */
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResultResponse<String> handleException(Exception e) {
        log.error("系统未知问题,异常类型:{}", e.getClass(), e);
        return ResultResponse.fail(CommonErrorEnum.ERROR_UNKNOW_EXCEPTION.getErrorCode(), CommonErrorEnum.ERROR_UNKNOW_EXCEPTION.getErrorMsg());
    }

    @ExceptionHandler(value = CommonException.class)
    public ResultResponse<Object> handleException(CommonException e) {
        ResultResponse<Object> errorResult = ResultResponse.fail(e.getErrorCode(), e.getErrorMsg());
        log.error(errorResult.getRequestId(), e);
        return errorResult;
    }

    /**
     * 参数校验异常处理
     *
     * @param e e
     * @return ResultResponse
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultResponse<Object> handleException(ConstraintViolationException e) {

        ResultResponse<Object> errorResult = ResultResponse.fail(
                CommonErrorEnum.ERROR_VAILD_EXCEPTION.getErrorCode(),
                CommonErrorEnum.ERROR_VAILD_EXCEPTION.getErrorMsg() + ":" + e.getLocalizedMessage());
        log.error(errorResult.getRequestId(), e);
        return errorResult;
    }

    /**
     * 无操作权限异常
     *
     * @param e e
     * @return ResultResponse
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    public ResultResponse<Object> handleException(AccessDeniedException e) {
        ResultResponse<Object> errorResult = ResultResponse.fail(
                "403", "没有操作权限，请联系系统管理员");
        log.error(errorResult.getRequestId(), e);
        return errorResult;
    }
}
